#!/bin/bash
# 宿主机硬盘SMART监控脚本（Linux版）
# 替换变量：{{HOST_ID}} {{TOKEN}}
HOST_ID={{HOST_ID}}
TOKEN={{TOKEN}}
API_URL="你的API地址/api/data_report.php"
SMARTCTL=/usr/local/sbin/smartctl

# =====================================
# 作者：老曹  QQ:1484743
# 版权声明：本程序为个人原创、开源程序，禁止用于任何违法用途，任何违法用途均与作者无关。
# 仅限学习交流，转载请注明出处。如需商用请联系作者。
# =====================================

# 检查并自动安装 wget（CentOS低版本自动识别rpm包）
if ! command -v wget >/dev/null 2>&1; then
  echo "未检测到wget，尝试自动安装..."
  if [ -x "$(which yum)" ]; then
    sudo yum install -y wget
    if ! command -v wget >/dev/null 2>&1; then
      echo "yum 安装失败，尝试rpm包离线安装..."
      centos_ver="$(rpm -q --qf '%{VERSION}' centos-release 2>/dev/null)"
      case "$centos_ver" in
        7.9*) rpm_url="http://vault.centos.org/7.9.2009/os/x86_64/Packages/wget-1.14-18.el7_6.1.x86_64.rpm" ;;
        7.6*) rpm_url="http://vault.centos.org/7.6.1810/os/x86_64/Packages/wget-1.14-18.el7.x86_64.rpm" ;;
        7.5*) rpm_url="http://vault.centos.org/7.5.1804/os/x86_64/Packages/wget-1.14-15.el7_4.1.x86_64.rpm" ;;
        7.4*) rpm_url="http://vault.centos.org/7.4.1708/os/x86_64/Packages/wget-1.14-15.el7_4.1.x86_64.rpm" ;;
        *) rpm_url="http://vault.centos.org/7.9.2009/os/x86_64/Packages/wget-1.14-18.el7_6.1.x86_64.rpm" ;;
      esac
      if command -v curl >/dev/null 2>&1; then curl -O $rpm_url; else echo "curl 不可用，尝试用 yum 安装 curl..."; sudo yum install -y curl; curl -O $rpm_url; fi
      sudo rpm -ivh --replacepkgs --replacefiles wget-*.rpm
      rm -f wget-*.rpm
    fi
  fi
  if [ -x "$(which apt)" ]; then sudo apt update && sudo apt install -y wget; fi
  if [ -x "$(which dnf)" ]; then sudo dnf install -y wget; fi
fi
if ! command -v wget >/dev/null 2>&1; then
  echo "wget 安装失败，请手动安装 wget 后重试。"
  exit 1
fi

# 检查并自动安装依赖（gcc、gcc-c++/g++、make、tar、bc）
for dep in gcc make tar bc; do
  if ! command -v $dep >/dev/null 2>&1; then
    echo "未检测到$dep，自动安装..."
    if [ -x "$(which yum)" ]; then sudo yum install -y $dep; fi
    if [ -x "$(which apt)" ]; then sudo apt update && sudo apt install -y $dep; fi
    if [ -x "$(which dnf)" ]; then sudo dnf install -y $dep; fi
  fi
  if ! command -v $dep >/dev/null 2>&1; then
    echo "$dep 安装失败，请手动安装 $dep 后重试。"
    exit 1
  fi
done
# 检查并自动安装 C++ 编译器
gpp_installed=0
if command -v g++ >/dev/null 2>&1; then
  gpp_installed=1
fi
if [ $gpp_installed -eq 0 ]; then
  echo "未检测到g++，自动安装..."
  if [ -x "$(which yum)" ]; then sudo yum install -y gcc-c++; fi
  if [ -x "$(which apt)" ]; then sudo apt update && sudo apt install -y g++; fi
  if [ -x "$(which dnf)" ]; then sudo dnf install -y gcc-c++; fi
fi
if ! command -v g++ >/dev/null 2>&1; then
  echo "g++ 安装失败，请手动安装 g++ 或 gcc-c++ 后重试。"
  exit 1
fi

check_smartctl() {
    if [ -x "$SMARTCTL" ]; then
        ver=$($SMARTCTL --version | head -n1 | grep -oE '[0-9]+\.[0-9]+' | head -n1)
        if [[ $(echo "$ver >= 7.4" | bc) -eq 1 ]]; then
            return 0
        fi
    fi
    return 1
}

if ! check_smartctl; then
    echo "未检测到新版 smartctl，自动下载安装 smartmontools 7.4..."
    cd /tmp
    # 多源依次尝试
    url_list=(
      "https://mirrors.ustc.edu.cn/sourceforge/smartmontools/smartmontools/7.4/smartmontools-7.4.tar.gz"
      "https://mirrors.tuna.tsinghua.edu.cn/sourceforge/smartmontools/smartmontools/7.4/smartmontools-7.4.tar.gz"
      "https://mirrors.aliyun.com/sourceforge/smartmontools/smartmontools/7.4/smartmontools-7.4.tar.gz"
      "https://downloads.sourceforge.net/project/smartmontools/smartmontools/7.4/smartmontools-7.4.tar.gz"
    )
    success=0
    for url in "${url_list[@]}"; do
      echo "尝试下载: $url"
      wget -O smartmontools-7.4.tar.gz "$url" && success=1 && break
    done
    if [ $success -ne 1 ]; then
      echo "所有源下载 smartmontools 7.4 失败，请手动下载安装。"
      exit 1
    fi
    tar zxvf smartmontools-7.4.tar.gz
    cd smartmontools-7.4
    ./configure && make && sudo make install
    cd /tmp
    rm -rf smartmontools-7.4*
    if ! check_smartctl; then
        echo "自动安装 smartctl 失败，请手动安装 smartmontools 7.4 及以上版本。"
        exit 1
    fi
fi

JQ=$(which jq)
if [ -z "$JQ" ]; then
  echo "未检测到jq，尝试自动安装..."
  if [ -x "$(which yum)" ]; then sudo yum install -y jq; fi
  if [ -x "$(which apt)" ]; then sudo apt update && sudo apt install -y jq; fi
  if [ -x "$(which dnf)" ]; then sudo dnf install -y jq; fi
  JQ=$(which jq)
fi
# 自动检测所有硬盘设备名（支持sda/vda/nvme等）
DEVICES=$(lsblk -d -n -o NAME | grep -E 'sd|vd|nvme' | awk '{print "/dev/"$1}')
for DEVICE in $DEVICES; do
  echo "==== 正在采集 $DEVICE ===="
  SMART_JSON=$($SMARTCTL -a -j $DEVICE 2>/dev/null)
  if [ -z "$SMART_JSON" ]; then
    echo "$DEVICE smartctl -a -j 输出为空，跳过。"
    continue
  fi
  # 检查是否为有效JSON
  echo "$SMART_JSON" | $JQ . >/dev/null 2>&1
  if [ $? -ne 0 ]; then
    echo "$DEVICE smartctl 输出不是有效JSON，跳过。"
    continue
  fi
  EXIT_STATUS=$(echo "$SMART_JSON" | $JQ -r '.smartctl.exit_status // 1')
  if [ "$EXIT_STATUS" != "0" ]; then
    echo "$DEVICE 无法获取SMART信息，跳过。"
    continue
  fi
  MODEL=$($SMARTCTL -i $DEVICE | grep 'Device Model' | awk -F: '{print $2}' | xargs)
  SERIAL=$($SMARTCTL -i $DEVICE | grep 'Serial Number' | awk -F: '{print $2}' | xargs)
  CAPACITY=$($SMARTCTL -i $DEVICE | grep 'User Capacity' | awk -F'[' '{print $1}' | tr -cd '0-9')
  JSON_DATA=$($JQ -n --arg hostId "$HOST_ID" --arg token "$TOKEN" --arg smart_json "$SMART_JSON" --arg device "$DEVICE" --arg model "$MODEL" --arg serial "$SERIAL" --arg capacity "$CAPACITY" '{hostId: ($hostId|tonumber), token: $token, smart_json: $smart_json, device: $device, model: $model, serial: $serial, capacity: ($capacity|tonumber)}')
  echo "上报数据：$JSON_DATA"
  curl -k -X POST -H "Content-Type: application/json" -d "$JSON_DATA" "$API_URL"
done
# 自动加入crontab，每6小时执行一次
CRON_CMD="/bin/bash $(readlink -f \"$0\") > /tmp/smart_monitor.log 2>&1"
CRON_EXPR="0 */6 * * * $CRON_CMD"
(crontab -l 2>/dev/null | grep -v "$CRON_CMD"; echo "$CRON_EXPR") | crontab -
echo "已自动将脚本加入crontab，每6小时执行一次。"
# 可手动查看：crontab -l 